package com.darryring.fast;

import android.app.Application;
import android.content.Context;
import android.util.DisplayMetrics;
import android.util.Log;

import com.darryring.fast.activitys.ErrorCrashActivity;
import com.darryring.fast.util.ApkUtil;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import cat.ereza.customactivityoncrash.CustomActivityOnCrash;

/**
 * Created by hljdrl on 15/12/11.
 */
public class DarryApplication extends Application {

    private String APP_TAG="FAST-LITE-ANDROID";

    private static DarryApplication mApplication = null;

    public static final DarryApplication getInstance(){
        return mApplication;
    }
    String TAG="DarryApplication";
    private int mScreenHeight;
    private int mScreenWidth;
    public final int getScreenHeight(){
        return mScreenHeight;
    }
    public final int getScreenWidth(){
        return mScreenWidth;
    }
    @Override
    public void onCreate() {
        mApplication = this;
        super.onCreate();
//        if (quickStart()) {
//            return;
//        }
        DisplayMetrics displayMetrics = new DisplayMetrics();
        displayMetrics = getResources().getDisplayMetrics();
        mScreenHeight = displayMetrics.heightPixels;
        mScreenWidth = displayMetrics.widthPixels;

        int pid = android.os.Process.myPid();
        String processAppName = ApkUtil.getAppName(pid,this);
        String _pkgName = getPackageName();
        if (processAppName == null || !processAppName.equalsIgnoreCase(_pkgName)) {
            Log.e(TAG, "enter the service process!");
            // "com.easemob.chatuidemo"为demo的包名，换到自己项目中要改成自己包名
            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }

        Log.i(TAG,"onCreate...");
        Log.i(TAG,"ScreenSize--->"+mScreenWidth+" x "+mScreenHeight);
        CustomActivityOnCrash.install(this);
        CustomActivityOnCrash.setErrorActivityClass(ErrorCrashActivity.class);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Log.i(TAG,"onLowMemory...");
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);

        Log.i(TAG,"onLowMemory--->level-->"+level);
    }

    public static void initImageLoader() {
        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this);
        // method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(getInstance());
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(70 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        if(!ImageLoader.getInstance().isInited()) {
            ImageLoader.getInstance().init(config.build());
        }
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        Log.i(APP_TAG, "onTerminate()....");
    }

//    //==================================================================
//    public static final String KEY_DEX2_SHA1 = "dex2-SHA1-Digest";
//    @Override
//    protected void attachBaseContext(Context base) {
//        super .attachBaseContext(base);
//        Log.d( "loadDex", "Application-->attachBaseContext ");
//        if (!quickStart()
////                && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP
//                ) {//>=5.0的系统默认对dex进行oat优化
//            if (needWait(base)){
//                waitForDexopt(base);
//            }
//            MultiDex.install (this );
//        } else {
//            return;
//        }
//    }
//    //
//    public boolean quickStart() {
//        if (StringUtil.contains( getCurProcessName(this), ":mini")) {
//            Log.d( "loadDex", ":mini start!");
//            return true;
//        }
//        return false ;
//    }
//    //neead wait for dexopt ?
//    private boolean needWait(Context context){
//        String flag = get2thDexSHA1(context);
//        Log.d( "loadDex", "dex2-sha1 "+flag);
//        SharedPreferences sp = context.getSharedPreferences(
//                PackageUtil.getPackageInfo(context). versionName, MODE_MULTI_PROCESS);
//        String saveValue = sp.getString(KEY_DEX2_SHA1, "");
//        return !StringUtil.equals(flag,saveValue);
//    }
//    /**
//     * Get classes.dex file signature
//     * @param context
//     * @return
//     */
//    private String get2thDexSHA1(Context context) {
//        ApplicationInfo ai = context.getApplicationInfo();
//        String source = ai.sourceDir;
//        try {
//            JarFile jar = new JarFile(source);
//            Manifest mf = jar.getManifest();
//            Map<String, Attributes> map = mf.getEntries();
//            Attributes a = map.get("classes2.dex");
//            return a.getValue("SHA1-Digest");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null ;
//    }
//    // optDex finish
//    public void installFinish(Context context){
//        SharedPreferences sp = context.getSharedPreferences(
//                PackageUtil.getPackageInfo(context).versionName, MODE_MULTI_PROCESS);
//        sp.edit().putString(KEY_DEX2_SHA1,get2thDexSHA1(context)).commit();
//    }
//
//
//    public static String getCurProcessName(Context context) {
//        try {
//            int pid = android.os.Process.myPid();
//            ActivityManager mActivityManager = (ActivityManager) context
//                    .getSystemService(Context. ACTIVITY_SERVICE);
//            for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
//                    .getRunningAppProcesses()) {
//                if (appProcess.pid == pid) {
//                    return appProcess. processName;
//                }
//            }
//        } catch (Exception e) {
//            // ignore
//        }
//        return null ;
//    }
//    public void waitForDexopt(Context base) {
//        Intent intent = new Intent();
//        ComponentName componentName = new
//                ComponentName( "com.darryring.fast", "com.darryring.fast.activitys.LoadResActivity");
//        intent.setComponent(componentName);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        base.startActivity(intent);
//        long startWait = System.currentTimeMillis ();
//        long waitTime = 10 * 1000 ;
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1 ) {
//            waitTime = 20 * 1000 ;//实测发现某些场景下有些2.3版本有可能10s都不能完成optdex
//        }
//        while (needWait(base)) {
//            try {
//                long nowWait = System.currentTimeMillis() - startWait;
//                Log.d(TAG , "loadDex-->wait ms :" + nowWait);
//                if (nowWait >= waitTime) {
//                    return;
//                }
//                Thread.sleep(200 );
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    //==================================================================
}
